package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import cn.eeepay.api.grpc.nano.PersonProto;
import cn.eeepay.api.grpc.nano.PersonApiServiceGrpc;
import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.PersonListAdapter;
import com.eeepay.eeepay_v2.model.PersonInfo;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/14 0014.\
 * 人员列表
 */
public class PersonListActivity extends ABBaseActivity implements AdapterView.OnItemClickListener, AbsListView.OnScrollListener {

    private TextView person_statistics;
    private ListView lv_person;
    private PersonListAdapter adapter;

    private String role;
    private String state;
    private String phone;

    private int page = 1;
    private int pageSize = 10;
    private int lastItem;

    private int sum = 0, normal = 0, abnormal = 0;//人员总数， 正常、 失效

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person_list;
    }

    @Override
    protected void initWidget() {
        person_statistics = getViewById(R.id.tv_person_statistics);
        lv_person = getViewById(R.id.lv_person_content);
        adapter = new PersonListAdapter(mContext);
        lv_person.setAdapter(adapter);

        if(bundle != null){
            role = bundle.getString("role");
            state = bundle.getString("state");
            phone = bundle.getString("phone");
            Log.i("TAG", role + state + phone);
            sendHttpRequest(0);
        }

    }

    @Override
    protected void eventOnClick() {
        lv_person.setOnItemClickListener(this);
        lv_person.setOnScrollListener(this);
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog("请稍等。。。");
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                PersonApiServiceGrpc.PersonApiServiceBlockingStub stub = PersonApiServiceGrpc
                        .newBlockingStub(channel)
                        .withDeadlineAfter(5, TimeUnit.SECONDS);
                PersonProto.PersonRequest request = new PersonProto.PersonRequest();
                request.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
                request.teamId = ConfigPorperties.getInstance().getTeamId();
                request.manage = role;
                request.status = state;
                request.mobilephone = phone;
                request.pageNo = page;
                request.pageSize = pageSize;
                PersonProto.PersonResponse response = stub.getPersonInfoRpc(request);
                return response;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (result == null) {
                    person_statistics.setText("查询失败");
                    return;
                }
                PersonProto.PersonResponse response = (PersonProto.PersonResponse) result;
                PersonProto.ResultMsgResponse resultMsg = response.resultMsg;
                String code = resultMsg.code;
                if ("false".equals(code)) {
                    LogUtils.d("codeInfo = " + resultMsg.codeInfo);
                    person_statistics.setText(resultMsg.codeInfo);
                    return;
                }
                PersonProto.PerMsg[] perMsg = response.perMsg;
                sum = response.total;
                if(page == 1){
                    normal = 0;
                    abnormal = 0;
                }
                List<PersonInfo> datas = new ArrayList<>();
                for (int i = 0; i < perMsg.length; i++) {
                    PersonInfo info = new PersonInfo();
                    LogUtils.d(Constant.TAG, " 下发的 id = " + perMsg[i].userId);
                    info.setId(perMsg[i].userId);
                    info.setName(perMsg[i].userName);
                    info.setPhone(perMsg[i].mobilephone);
                    info.setEmail(perMsg[i].email);
                    info.setRole(perMsg[i].manage);
                    info.setState(perMsg[i].status);
                    LogUtils.d("TAG", "onPostExecute:  personInfo = " + info);
                    datas.add(info);
                    if ("失效".equals(perMsg[i].status)) {
                        abnormal++;
                    } else {
                        normal++;
                    }
                }
                person_statistics.setText("人员总数: " + sum + " ( 正常: " + normal + ", 失效: " + abnormal + ") ");
                if (page == 1) {
                    adapter.setList(datas);
                } else {
                    adapter.addAll(datas);
                }

            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PersonInfo data = adapter.getData(position);
        Bundle bundle = new Bundle();
        bundle.putSerializable("personInfo", data);
        goActivityForResult(PersonEditActivity.class, bundle, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        sendHttpRequest(0);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (lastItem == adapter.getCount()
                && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            if(page * pageSize < sum){
                page++;
                sendHttpRequest(0);
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        lastItem = firstVisibleItem + visibleItemCount;
    }
}
